<template>
    <div class="avatar-menu">
        <el-dropdown trigger="click">
            <span class="el-dropdown-link">
                <el-avatar :src="userAvatar" size="small" />
            </span>
            <template #dropdown>
                <el-dropdown-menu v-if="token">
                    <el-dropdown-item @click="goProfile">Profile</el-dropdown-item>
                    <el-dropdown-item @click="goTaskPage">Task</el-dropdown-item>
                    <el-dropdown-item @click="logout">Logout</el-dropdown-item>
                </el-dropdown-menu>
                <el-dropdown-menu v-else>
                    <el-dropdown-item @click="goLogin">Login</el-dropdown-item>
                    <el-dropdown-item @click="goRegister">Register</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script setup lang="ts">
    import { computed, ref, watch } from 'vue';
    import { useRouter } from 'vue-router';
    import { useAuth, token } from '@/common/useAuth';
    import { fullUrl } from '@/common/util';

    const { user, logout } = useAuth();
    const router = useRouter();
    const userAvatar = ref<string | null>(null);

    function goProfile() {
        router.push({ name: 'userpage' });
    }

    function goLogin() {
        router.push({ name: 'login' });
    }

    function goTaskPage() {
        router.push({ name: 'taskpage' });
    }

    function goRegister() {
        router.push({ name: 'register' });
    }


    watch(() => user.value?.profile?.avatar, (val) => {
        console.log(user)
        if (val) {
            // 加上时间戳避免浏览器缓存（也可以用文件的版本号或 mtime）
            userAvatar.value = `${fullUrl(val)}?v=${Date.now()}`;
        } else {
            userAvatar.value = null;
        }
    }, { immediate: true, deep: true });
</script>

<style scoped>
    .avatar-menu {
        position: static;
        display: inline-flex;
        align-items: center; /* 垂直居中 avatar */
        flex: 0 0 auto;      /* 不被挤压也不伸展 */
        margin-left: 0.5rem; /* 与 nav-links 保持间距，可按需调整 */
        z-index: 2;          /* 保证在下拉、折叠菜单等之上（如果需要） */
    }
    .avatar-menu .el-dropdown-link {
        display: inline-flex;
        align-items: center;
        padding: 4px;
        border-radius: 6px;
    }
</style>
